package org.study;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class AtomicDemo {

    public First demo;

    public String subField;

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        AtomicDemo thiz = new AtomicDemo();
        Unsafe unsafe = getUnsafe();
        long offset = unsafe.objectFieldOffset(AtomicDemo.class.getDeclaredField("demo"));
        System.out.println(offset);
        First first = new First();
        boolean b = unsafe.compareAndSwapObject(thiz, offset, null, first);
        Object value = unsafe.getObject(thiz, offset);
        System.out.println(value);
        System.out.println(first);
        boolean bc = unsafe.compareAndSwapObject(thiz, offset, first, new First());
        System.out.println(b);
        System.out.println(bc);
    }

    public static Unsafe getUnsafe() throws IllegalAccessException, NoSuchFieldException {
        Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
        //Field unsafeField = Unsafe.class.getDeclaredFields()[0]; //也可以这样，作用相同
        unsafeField.setAccessible(true);
        Unsafe unsafe =(Unsafe) unsafeField.get(null);
        return unsafe;
    }


    static class First {

        public int value = 1;

        @Override
        public boolean equals(Object obj) {
            return super.equals(obj);
        }
    }
}
